const global = getApp().globalData;
const Api = global.Api;
const wxApi = global.wxApi;
const topicApi = global.topicApi
Page({
  data: {
    currentTopic: null,
    topicCanStudy: true,
    associatedBooks: [],
    unsubedBooksShow: false
  },
  onLoad(options) {
    wxApi.setNavTitle('知识点学习')
    this.init( options );
  },
  
  init(options) {
    let self = this;
    let topic = options.topic;
    this.topicInit(topic);
  },
  /**
   * 一般模式（单词不可切换）--初始化
   *
   */
  topicInit(topic) {
    
    topic = wxApi.decodeURI(topic);
    this.topicIndex = topic.index;
    this.bookId = topic.curTextbookId || null;
    this.loadTopicDetail(topic);
  },
  getLastPage() {
    console.log(wxApi.lastPage())
    return wxApi.lastPage();
  },
  /**
   * 获取上一页面已加载的topics
   *
   * @returns topics
   */
  getLastPageTopics() {
    console.log(this.getLastPage().topics);
    return this.getLastPage().topics;
  },
  getLastPageTopicTotalNum() {
    return this.getLastPage().topicTotalNum;
  },
  /**
   * 根据知识点简要信息，获取知识点详情
   *
   * @param {Object} topic
   */
  loadTopicDetail(topic) {
    wx.showLoading({
      title: '',
      mask: true
    });
    let params = {};
    topic.unitId && (params.unitId = topic.unitId)
    topic.lessonId && (params.lessonId = topic.lessonId)
    topicApi.getTopicDetailByID(topic.id, params, (res) => {
      console.log('加载知识点详情：')
      console.log(res);
      if (res === null) res = topic
      let currentTopic = res;
      wx.hideLoading();
      // 如果是单词
      this.setCurrentTopic(currentTopic)
    })
  },
  /**
   * 设置当前显示知识点
   *
   * @param {Object} topic
   */
  setCurrentTopic(topic) {
    console.log('current topic:')
    console.log(topic)
    this.topicCanStudy(topic);
    if (topic.curLessonName) {
      let number = topic.curLessonNumber + " " || "";
      let title = number + topic.curLessonName
      wxApi.setNavTitle(title)
    }
    this.setData({
      currentTopic: topic
    })
  },
  /**
   * 获取当前显示知识点
   *
   * @returns Obeject
   */
  getCurrentTopic() {
    return this.data.currentTopic;
  },
    /**
   * 订阅课本
   */
  onSubscribed() {
    let topic = this.getCurrentTopic();
    topicApi.getAssocitatedBooks(topic.id, books => {
      console.log('加载知识点关联的课本');
      console.log(books);
      if (books.length === 1) {
        let params = {
          id: books[0].id
        }
        wxApi.redirectTo('../book-detail/book-detail', params);
      } else {
        this.setData({
          associatedBooks: books,
          unsubedBooksShow: true
        })
      }
    })  
  },
  /**
   * 选中未订阅课本
   *
   */
  onUnsubedBookTap(e) {
    let unsubedBook = e.detail;
    let params = {
      id: unsubedBook.id,
      name: unsubedBook.name
    }
    let path = '../book-detail/book-detail';
    wxApi.navigateTo(path, params);
  },
  topicCanStudy(topic) {
    let canStudy = JSON.parse(topic.textbookSubscribed) || JSON.parse(topic.free);
    this.setData({
      topicCanStudy: canStudy
    })
    return canStudy;
  },
  /**
   * 上一个知识点
   */
  lastTopic() {
    let totalTopics = this.getLastPageTopics();
    if (!totalTopics) return;
    let topicLen = totalTopics.length;
    this.topicIndex --
    if (this.topicIndex < 0) {
      this.topicIndex = 0;
      wx.showToast({
        title: '已经是第一个知识点',
        icon: 'none'
      })
      return;
    }
    this.loadTopicDetail(totalTopics[this.topicIndex]);
  },

  /**
   * 下一个知识点
   */
  nextTopic() {
    let totalTopics = this.getLastPageTopics()
    if (!totalTopics) return;
    let topicsLen = totalTopics.length; 
    let topicTotalNum = this.getLastPageTopicTotalNum();
    this.topicIndex ++;
    if (this.topicIndex < topicsLen) {
      // 当前下标小于已加载知识点总量
      this.loadTopicDetail(totalTopics[this.topicIndex]);
    } else if (this.topicIndex >= topicsLen && this.topicIndex < topicTotalNum) {
      // 当前下标等于已加载知识点总量，且小于数据库知识点总量
      this.laodMoreLastPageTopics(hasMore => {
        if (hasMore) {
          this.loadTopicDetail(this.getLastPageTopics()[this.topicIndex])
        } else {
          this.topicIndex --;
          wx.showToast({
            title: '已经是最后一个知识点',
            icon: 'none'
          })
        }
      })
    } else {
      // 当前下标大于等于数据库知识点总量
      this.topicIndex --;
      wx.showToast({
        title: '已经是最后一个知识点',
        icon: 'none'
      })
    }
  },
  onTagTap(e) {
    let tag = e.detail;
    let params = {
      searchParam: wxApi.encodeURI({
        query: {
          tagId: tag.id
        },
        title: tag.name
      })
    }
    wxApi.navigateTo('../topics/topics', params);
  },
  /**
   * 调用上一级页面加载更多方法
   *
   * @param {Function} fn
   */
  laodMoreLastPageTopics(fn) {
    this.getLastPage().loadMore(hasMore => {
      fn(hasMore);
    })
  },
})